package cn.swenty.backstage.base.web.system.controller;

import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.swenty.backstage.base.web.system.entity.SysResFormMap;
import cn.swenty.backstage.base.web.system.entity.SysRoleFormMap;
import cn.swenty.backstage.base.web.system.entity.SysRoleResFormMap;
import cn.swenty.backstage.base.web.system.entity.SysUserFormMap;
import cn.swenty.backstage.base.web.system.entity.SysUserRoleFormMap;
import cn.swenty.backstage.base.web.system.service.DepartService;
import cn.swenty.backstage.base.web.system.service.FunctionService;
import cn.swenty.backstage.base.web.system.service.RoleService;
import cn.swenty.backstage.base.web.system.service.UserInfoService;
import cn.swenty.backstage.framework.common.model.Function;
import cn.swenty.backstage.framework.common.util.Bean2MapUtils;
import cn.swenty.backstage.framework.common.util.DateUtil;
import cn.swenty.backstage.framework.common.util.StringUtil;
import cn.swenty.backstage.framework.controller.BaseController;
import cn.swenty.backstage.framework.database.entity.Entity;
import cn.swenty.backstage.framework.database.plugin.PageView;
import cn.swenty.backstage.framework.util.Common;
import cn.swenty.backstage.framework.util.IdGenerator;

/**
 * 角色
 * @author  liukang
 */
@Controller
@RequestMapping("/system/roleInfo/")
public class RoleInfoController extends BaseController {
	
	@Inject
	private RoleService roleService;
	
	@Inject
	private FunctionService functionService;
	
	
	@Inject
	private UserInfoService userInfoService;
	
	
	@Inject
	private DepartService departService;
	
	
	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		
	
		return Common.BACKGROUND_PATH + "/system/role/list";
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String pageNow,
			String pageSize) throws Exception {
		SysRoleFormMap sysRoleFormMap = getFormMap(SysRoleFormMap.class);

		if(StringUtil.isNull(sysRoleFormMap.getStr("orderby"))){
			sysRoleFormMap.put("column", "sequence");
			sysRoleFormMap.put("sort", "asc");
			sysRoleFormMap.put("orderby", "order by sequence");
		}
		sysRoleFormMap=toFormMap(sysRoleFormMap, pageNow, pageSize,sysRoleFormMap.getStr("orderby"));
        pageView.setRecords( roleService.findRolePage(sysRoleFormMap));
		return pageView;
	}

	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/role/info";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String addEntity() throws Exception {
		SysRoleFormMap sysRoleFormMap = getFormMap(SysRoleFormMap.class);
		roleService.save(sysRoleFormMap);
		return "success";
	}

	@ResponseBody
	@RequestMapping("deleteEntity")
	public String deleteEntity() throws Exception {
			String ids = getPara("ids");		
			if(!ids.isEmpty()){
				String [] is = ids.split(",");
				SysRoleFormMap roleFormMap = new SysRoleFormMap();
				SysRoleResFormMap roleResFormMap = new SysRoleResFormMap();
				SysUserRoleFormMap userRoleFormMap = new SysUserRoleFormMap();
				roleFormMap.put("$in_role_id",is);	//角色表
				roleResFormMap.put("$in_role_id",is);	//角色菜单
				userRoleFormMap.put("$in_role_id",is);//用户角色	
				roleFormMap.delete();
				roleResFormMap.delete();
				userRoleFormMap.delete();
			}
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("role_id");
		if(Common.isNotEmpty(id)){
			model.addAttribute("role", userInfoService.get(SysRoleFormMap.class, id));
		}
		return Common.BACKGROUND_PATH + "/system/role/info";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String editEntity() throws Exception {
		SysRoleFormMap sysRoleFormMap = getFormMap(SysRoleFormMap.class);
		sysRoleFormMap.update();
		return "success";
	}
	
	@ResponseBody
	@RequestMapping("findRoleFunction")
	public List<SysResFormMap> findRoleFunction(){
		String roleId  = getPara("role_id");
		return functionService.findByRole(roleId);
	}
	
	@ResponseBody
	@RequestMapping("findByParent")
	public List<? extends Entity> findFunctionByParent(){
		String parentId  = getPara("parent_id");
		SysResFormMap formMap = new SysResFormMap();
		formMap.put("parent_id", parentId);
		return formMap.query();
	}
	
	
	@RequestMapping("selRole")
	public String seletRole(Model model) throws RuntimeException {
		SysRoleFormMap roleFormMap = getFormMap(SysRoleFormMap.class);
		
		try {
			Object userId = roleFormMap.get("user_id");
			model.addAttribute("userId", userId);
			if(null!=userId){
				List<SysRoleFormMap> list = roleService.seletUserRole(roleFormMap);
				String ugid = "";
			for (SysRoleFormMap sysRoleFormMap : list) {
				ugid += sysRoleFormMap.get("role_id")+",";
			}
			model.addAttribute("txtRoleSelect", ugid);
			model.addAttribute("userRole", list);
			if(StringUtils.isNotBlank(ugid)){
				roleFormMap.put("$nin_role_id", ugid.split(","));
			}
		
			List<SysRoleFormMap> roles = roleService.queryList(roleFormMap);
			model.addAttribute("role", roles);
			}
		} catch (Exception e) {
				System.out.println(e.getMessage());
				e.fillInStackTrace();
		}	
			
		return Common.BACKGROUND_PATH + "/system/user/roleSelect";
	}


	
	
	/**
	 * 增加权限中间表
	 * @return
	 */
	@ResponseBody
	@RequestMapping("addRoleFunctionEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String addRoleFunctionEntity(Model model,String date,String roleId){
			String data = getPara("data");
			System.out.println(data);
			String role_id = getPara("roleId");
			
			if(!role_id.isEmpty()){
				SysRoleResFormMap roleResFormMap = new SysRoleResFormMap();
				roleResFormMap.put("$in_role_id", role_id.split(","));
				roleResFormMap.delete();
			}
			if(!data.isEmpty()){
				SysRoleResFormMap sysRoleResFormMap= new SysRoleResFormMap();
				String  functionId[] =data.split(",");
				for (String string : functionId) {
					sysRoleResFormMap.set("id", IdGenerator.getNextId());
					sysRoleResFormMap.set("role_id", role_id);
					sysRoleResFormMap.set("function_id", string);
					sysRoleResFormMap.put("create_time", DateUtil.getTimestamp());
					roleService.save(sysRoleResFormMap);
				}
			}
			return "success";
		 
	}
	
	/**
	 * 根据权限id查询所有用户
	 * @param model
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping("findUserRole")
	public String findUserRole(Model model) throws Exception {
		String role_id = getPara("role_id");
		model.addAttribute("role_id", role_id);
		return Common.BACKGROUND_PATH + "/system/role/roleUserList";
	}

	
	
	
	
	
	@ResponseBody
	@RequestMapping("findUserByPage")
	public PageView findUserByPage(String pageNow,
			String pageSize) throws Exception {
		String roleId= getPara("role_id");
		SysUserRoleFormMap sysUserRoleFormMap = getFormMap(SysUserRoleFormMap.class);
		sysUserRoleFormMap.put("role_id", "'"+roleId+"'");
		sysUserRoleFormMap=toFormMap(sysUserRoleFormMap, pageNow, pageSize,sysUserRoleFormMap.getStr("orderby"));
        pageView.setRecords( userInfoService.findUserByRoleId(sysUserRoleFormMap));
		return pageView;
	}
	
	
	
	/**
	 * 删除用户与角色的关联关系
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("deleteUserRole")
	public String deleteUserRole(Model model) throws Exception {
		String role_id = getPara("role_id");
		String  userIds = getPara("userIds");
		SysUserRoleFormMap  userRoleBean  =new  SysUserRoleFormMap();
		userRoleBean.set("userIds", userIds.split(","));
		userRoleBean.set("role_id", role_id);
		roleService.delUserRole(userRoleBean);
		
	return "success";
	}

	
	
	@RequestMapping("userList")
	public String userList(Model model) throws Exception {
		
		getHttpRequest().setAttribute("list",departService.findDeptTree());
		getHttpRequest().setAttribute("hiddenDeptTree", departService.findHiddens());
		getHttpRequest().setAttribute("roleId",getPara("roleId"));
		
		return Common.BACKGROUND_PATH + "/system/role/addUserList";
	}
	
	@ResponseBody
	@RequestMapping("showByPage")
	public PageView showByPage( String pageNow,
			String pageSize,String column,String sort) throws Exception {
		SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
		sysUserFormMap=toFormMap(sysUserFormMap, pageNow, pageSize,sysUserFormMap.getStr("orderby"));
		sysUserFormMap.put("column", column);
		sysUserFormMap.put("sort", sort);
		sysUserFormMap.put("state", 0);   //默认全讯全部
		String dept_id=getPara("deptId");
		if(Common.isNotEmpty(dept_id)){
			sysUserFormMap.put("dept_id", dept_id);
		}
        pageView.setRecords(userInfoService.findUserPage(sysUserFormMap));//不调用默认分页,调用自已的mapper中findUserPage
        return pageView;
	}
	
	
	
	
	
	
	/**
	 * 查询当前部门下用户
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("findUserByDeptId")
	public PageView findUserByDeptId(String pageNow,
			String pageSize,String column,String sort) {
		SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
		sysUserFormMap=toFormMap(sysUserFormMap, pageNow, pageSize,sysUserFormMap.getStr("orderby"));
		sysUserFormMap.put("column", column);
		sysUserFormMap.put("sort", sort);
		String dept_id=getPara("deptId");
		if(Common.isNotEmpty(dept_id)){
			sysUserFormMap.put("dept_id", dept_id);
		}
		String state =(String) sysUserFormMap.get("state");
		if(!Common.isNotEmpty(state) ||state.equals("2")){
			sysUserFormMap.put("state", null);   //默认全讯全部
		}
		
        pageView.setRecords(userInfoService.findUserByDeptId(sysUserFormMap));//不调用默认分页,调用自已的mapper中findUserPage
        return pageView;
	}
	

	@ResponseBody
	@RequestMapping("addUserRoleEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String addUserRoleEntity() throws Exception {
		String userIds=getPara("ids");
		String roleId=getPara("roleId");
		roleService.saveUserRole(roleId, userIds.split(","));	
	
		return "success";
	}
	
	/**
	 * 分配权限界面
	 * @param model
	 * @return
	 */
	@RequestMapping("permissions")
	public String permissions(Model model) throws Exception {
		
		//查询树装菜单
		List<SysResFormMap> listFunction=	functionService.queryAll(SysResFormMap.class);
		List<Function> list =null;
		list = Bean2MapUtils.maps2Objects(listFunction, Function.class);
		Collections.sort(list);
		getHttpRequest().setAttribute("function_tree",list);
		//将上级页面的角色id传递给下一个页面
		String role_id= getPara("role_id");
		model.addAttribute("role_id",role_id);
		//选中的值
		String roleFunctions = "";
		List<SysResFormMap> formMaps  = functionService.findByRole(role_id);
		if(formMaps!=null){
			for(SysResFormMap srf:formMaps){
				roleFunctions+=srf.getStr("function_id")+",";
			}
		}
		getHttpRequest().setAttribute("roleFunctions",roleFunctions);
		 
		//需要隐藏的值
	   SysResFormMap sysResFormMap= new SysResFormMap();
		sysResFormMap.put("state", 1);
		List<SysResFormMap> hiddens= functionService.findResHiddens(sysResFormMap);
		String ress="";
		for (SysResFormMap string : hiddens) {
			if(string.get("function_id")!=null){
				ress +=string.get("function_id")+",";
			}
		}
		getHttpRequest().setAttribute("hiddenResTree", ress);
		
		return Common.BACKGROUND_PATH + "/system/role/functionList";
	}
	
	/**
	 * 查询当前级别菜单
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("functions")
	public PageView findByPage(String pageNow,
			String pageSize,String column,String sort) {
		SysResFormMap function = getFormMap(SysResFormMap.class);
		String functionId=getPara("parent_id");
		if(!functionId.equals("aaa")){
			function.put("parent_id", getPara("parent_id"));
		}
		function=toFormMap(function, pageNow, pageSize,function.getStr("orderby"));
		function.put("column", column);
		function.put("sort", sort);
		 function.put("orderby", "order by squence desc");
		pageView.setRecords(functionService.findByPage(function));
		return pageView;
	}

	@ResponseBody
	@RequestMapping("saveRoleFunction")
	public String saveRoleFunction() throws Exception {
		String ids=getPara("ids");
		String roleId=getPara("role_id");
		roleService.saveRoleFunction(roleId, ids.split(","));
		return "success";
	}
	
	
	
}